package rpc

import (
	"context"
	"encoding/json"
	proto "gykjgit.dccnet.com.cn/chain/proto/swarm"
	"gykjgit.dccnet.com.cn/chain/swarm/client"
	"time"
)

type ServiceServer struct {
}

func (s *ServiceServer) Logs(ctx context.Context, in *proto.ReqServiceLogs) (*proto.RespServiceLogs, error) {
	data, err := client.Obtain().Service().Logs(ctx, in.ServiceID, time.Unix(in.Since.Sec, in.Since.Nsec), time.Unix(in.Until.Sec, in.Until.Nsec))
	if nil != err {
		return &proto.RespServiceLogs{Code: proto.Code_fail, ErrMsg: err.Error()}, err
	}
	return &proto.RespServiceLogs{Code: proto.Code_success, Logs: data}, nil
}

func (s *ServiceServer) List(ctx context.Context, _ *proto.ReqServiceList) (*proto.RespServiceList, error) {
	ss, err := client.Obtain().Service().List(ctx)
	if nil != err {
		return &proto.RespServiceList{Code: proto.Code_fail, ErrMsg: err.Error()}, err
	}
	data, err := json.Marshal(ss)
	if nil != err {
		return &proto.RespServiceList{Code: proto.Code_fail, ErrMsg: err.Error()}, err
	}
	return &proto.RespServiceList{Code: proto.Code_success, Services: data}, nil
}

func (s *ServiceServer) Inspect(ctx context.Context, in *proto.ReqServiceInspect) (*proto.RespServiceInspect, error) {
	cJson, data, err := client.Obtain().Service().Inspect(ctx, in.ServiceID)
	if nil != err {
		return &proto.RespServiceInspect{Code: proto.Code_fail, ErrMsg: err.Error()}, err
	}
	containerBytes, err := json.Marshal(cJson)
	if nil != err {
		return &proto.RespServiceInspect{Code: proto.Code_fail, ErrMsg: err.Error()}, err
	}
	return &proto.RespServiceInspect{Code: proto.Code_success, Service: containerBytes, Data: data}, nil
}

func (s *ServiceServer) Resource(ctx context.Context, in *proto.ReqServiceResources) (*proto.RespServiceResources, error) {
	r, err := client.Obtain().Service().Resources(ctx, in.ServiceID)
	if nil != err {
		return &proto.RespServiceResources{Code: proto.Code_fail, ErrMsg: err.Error()}, err
	}
	data, err := json.Marshal(r)
	if nil != err {
		return &proto.RespServiceResources{Code: proto.Code_fail, ErrMsg: err.Error()}, err
	}
	return &proto.RespServiceResources{Code: proto.Code_success, Resource: data}, nil
}

func (s *ServiceServer) ResourceAll(ctx context.Context, _ *proto.ReqServiceResourcesAll) (*proto.RespServiceResourcesAll, error) {
	stats, err := client.Obtain().Service().ResourcesAll(ctx)
	if nil != err {
		return &proto.RespServiceResourcesAll{Code: proto.Code_fail, ErrMsg: err.Error()}, err
	}
	data, err := json.Marshal(stats)
	if nil != err {
		return &proto.RespServiceResourcesAll{Code: proto.Code_fail, ErrMsg: err.Error()}, err
	}
	return &proto.RespServiceResourcesAll{Code: proto.Code_success, Resource: data}, nil
}
